using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using elibrary.Classes;
using elibrary.Models;
using elibrary.Models.Entities;

namespace elibrary.Models.Managers
{
	public class UserOrderItemManager
	{
		private DataContext ctx;
		private DbSet<UserOrderItem> orderItems;

		public UserOrderItemManager(DataContext ctx)
		{
			this.ctx = ctx;
			this.orderItems = ctx.orderItems;
		}

		public void add(UserOrderItem item,bool autoSave=true)
		{
			orderItems.Add(item);
			
			if (autoSave)
				ctx.SaveChanges();
		}

		public UserOrderItem get(int id)
		{
			return orderItems.SingleOrDefault(q => q.id == id);
		}

		public List<UserOrderItem> getByBookOrderId(int oid, int bid)
		{
			return Utilities.ensureRs<UserOrderItem>(orders.Where(q => q.orderId == oid && 
				q.bookId == bid));
		}

		public bool hasBookByOrderId(int oid, int bid)
		{
			return orders.Where(q => q.orderId == oid && q.bookId == bid).Any();
		}

		public bool hasByOrderId(int oid)
		{
			return orders.Where(q => q.orderId == oid).Any();
		}

		public bool hasByBookId(int bid)
		{
			return orders.Where(q = q.bookId == bid).Any();
		}

        public List<UserOrderItem> getAllByOrder(int oid)
        {
            return Utilities.ensureRs<UserOrderItem>(orderItems.Where(q => q.orderId == oid));
        }

		public void delete(int id,bool autoSave=true)
		{
			delete(get(id),autoSave);
		}

		public void delete(UserOrderItem item,bool autoSave=true)
		{
			if (item == null)
				return;

			orderItems.Remove(item);

			if (autoSave)
				ctx.SaveChanges();
		}
    }
}